package com.appspot.simplebookmarks.service;

import java.util.Date;
import java.util.List;

import org.slim3.datastore.Datastore;

import com.appspot.simplebookmarks.meta.LastAccessCollectionMeta;
import com.appspot.simplebookmarks.model.Collection;
import com.appspot.simplebookmarks.model.LastAccessCollection;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;

public class LastAccessCollectionService {

    private LastAccessCollection get(String author) {
        LastAccessCollectionMeta e = LastAccessCollectionMeta.get();
        LastAccessCollection lastAccessCollection =
            Datastore.query(e).filter(e.author.equal(author)).asSingle();
        if (lastAccessCollection == null) {
            CollectionService service = new CollectionService();
            List<Collection> list = service.getList(author);
            lastAccessCollection = new LastAccessCollection();
            lastAccessCollection.setAuthor(author);
            lastAccessCollection.setCollectionKey(list.get(0).getKey());
            Transaction tx = Datastore.beginTransaction();
            Datastore.put(lastAccessCollection);
            tx.commit();
        }
        return lastAccessCollection;
    }

    private LastAccessCollection update(LastAccessCollection lastAccessCollection) {
        if (lastAccessCollection != null && lastAccessCollection.getKey() != null) {
            Transaction tx = Datastore.beginTransaction();
            Datastore.put(lastAccessCollection);
            tx.commit();
        }
        return lastAccessCollection;
    }

    public LastAccessCollection updateLastAccess(String author, Key key) {
        LastAccessCollection lastAccessCollection = this.get(author);
        lastAccessCollection.setCollectionKey(key);
        lastAccessCollection.setUpdateDate(new Date());
        return this.update(lastAccessCollection);
    }

    public Key getCurrentCollectionKey(String author) {
        LastAccessCollection lastAccessCollection = this.get(author);
        return lastAccessCollection.getCollectionKey();
    }
}
